// order-submit.js
var api = require('../../api.js');
var utils = require('../../utils.js');
var util = require('../../utils/util.js');
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgServer :  api.default.img_server,
        total_price: 0,
        address: null,
        express_price: 0.00,
        content: '',
        offline: 0,
        express_price_1: 0.00,
        name: "",
        discounted_price: 0.00,
        peisongType: 'kd', // 配送方式 kd,zq 分别表示快递/到店自取
        mobile: "",
        pay_type:3 //支付方式，3为余额支付，2为微信支付
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var page = this;
        page.setData({
            options: options,
            store: wx.getStorageSync("store")
        });
    },
    bindkeyinput: function (e) {
        this.setData({
            content: e.detail.value
        });
    },
    KeyName: function (e) {
        this.setData({
            name: e.detail.value
        });
    },
    KeyMobile: function (e) {
        this.setData({
            mobile: e.detail.value
        });
    },
    getOffline: function (e) {
        var express = this.data.express_price;
        var express_1 = this.data.express_price_1;
        var offline = e.target.dataset.index;
        if (offline == 1) {
            this.setData({
                offline: offline,
                express_price: 0,
                express_price_1: express
            });
        } else {
            this.setData({
                offline: offline,
                express_price: express_1
            });
        }
    },
    orderSubmit: function (e) {
        var page = this;
        wx.requestSubscribeMessage({
          tmplIds: ['bPgXd4I-7E-GYafPJSNJEJjxU4EVTAFLapg_fSm-Ilg','RQh2jFDKYOx7tbOF68TUZTmDVJNGkTgB1ejL0I9Xh8k','qZOpyTxHMMB9EibgkUtm5mv9_lkQ09PYvwzdw6-pzqw'],
          success(res) {
              page.orderSubmit2(e);
            console.log(res)
          }
        })
    },
    orderSubmit2: function (e) {
		var access_token = wx.getStorageSync("access_token");
        util.submitFormId(e.detail.formId, '2');
        var page = this;
        var offline = page.data.offline;
        var peisongType = page.data.peisongType;
        var data = {};
        data.type=3;
		data.userid=access_token;
        data.formId=e.detail.formId;
        data.page='pages/order-detail/order-detail';
        if (peisongType != 'zt') {
            if (!page.data.address || !page.data.address.id) {
                wx.showToast({
                    title: "请选择收货地址",
                    image: "/images/icon-warning.png",
                });
                return;
            }
            data.addressId = page.data.address.id;
        } else {
            // data.address_name = page.data.name;
            // data.address_mobile = page.data.mobile;
            // if (page.data.shop.id)
            //     data.shop_id = page.data.shop.id;
        }
        data.offline = offline;
        if (page.data.options.cart_id_list) {
            data.cartIds = page.data.options.cart_id_list;
            data.type=2;
        }
        if (page.data.options.goods_info) {
            var info  = JSON.parse(page.data.options.goods_info);
            data.type=1;
            data.count = info.count;
            data.cartId = info.cartId;
        }
        if (page.data.picker_coupon) {
            data.couponId = page.data.picker_coupon.id;
        }
        if (page.data.content) {
            data.note = page.data.content
        }
        wx.showLoading({
            title: "正在提交",
            mask: true,
        });
        data.payType = page.data.pay_type
        data.platform=1;
			
		console.log('orderData:'+JSON.stringify(data));
			
        //提交订单
        app.request({
            url: api.order.submit,
            data: data,
            success: function (res) {
                if (res.code == 200) {
                    setTimeout(function () {
                        wx.hideLoading();
                    }, 1000);
                    setTimeout(function () {
                        page.setData({
                            options: {},
                        });
                    }, 1);
                  console.log("res")
                    console.log(res)
                    var order_id = res.data[0].order.id;
                    for(var i=1;i<res.data.length;i++){
                      order_id += ","+res.data[i].order.id
                    }

                    //获取支付数据
                    app.request({
                        url: api.order.pay_data,
                        data: {
                            id: order_id,
                          formId: e.detail.formId,
                            payType: 2,
                        }, 
                        success: function (res) {
                            console.log(res);
                            //余额支付成功
                            if(res.code ==201){
                              wx.redirectTo({
                                url: "/pages/payresult/payresult?order=" + order_id+"&paytype=3",
                              });
                            }
                            //余额支付失败
                          if (res.code == 202) {
                            wx.showModal({
                              title: "提示",
                              content: "余额支付失败，请充值后购买",
                              showCancel: false,
                              confirmText: "确认",
                              success: function (res) {
                                if (res.confirm) {
                                  wx.redirectTo({
                                    url: "/pages/order/order?status=0",
                                  });
                                }
                              }
                            });
                          }
                            if (res.code == 200) {
                                //发起支付
                                wx.requestPayment({
                                    timeStamp: res.data.timeStamp,
                                    nonceStr: res.data.nonceStr,
                                    package: res.data.package,
                                    signType: res.data.signType,
                                    paySign: res.data.paySign,
                                    success: function (e) {
                                        console.log('1');
                                        console.log(e);
                                      wx.requestSubscribeMessage({
                                        tmplIds: ['bPgXd4I-7E-GYafPJSNJEAQMuptkU_SYG1OscN7MM0o'],
                                        success(res) {
                                          console.log(res)
                                        },
                                        fail(error) {
                                          console.log(error)
                                        }
                                      });
                                        wx.redirectTo({
                                          url: "/pages/payresult/payresult?order=" + order_id + "&paytype=2",
                                        });
                                    },
                                    fail: function (e) {
                                        console.log('2');
                                        console.log(e);
                                    },
                                    complete: function (e) {
                                        console.log('3');
                                        console.log(e);
                                        if (e.errMsg == "requestPayment:fail" || e.errMsg == "requestPayment:fail cancel") {//支付失败转到待支付订单列表
                                            wx.showModal({
                                                title: "提示",
                                                content: "订单尚未支付",
                                                showCancel: false,
                                                confirmText: "确认",
                                                success: function (res) {
                                                    if (res.confirm) {
                                                        wx.redirectTo({
                                                            url: "/pages/order/order?status=0",
                                                        });
                                                    }
                                                }
                                            });
                                            return;
                                        }
                                        if (e.errMsg == "requestPayment:ok") {
                                            return;
                                        }
                                        wx.redirectTo({
                                            url: "/pages/order/order?status=1",
                                        });
                                    },
                                });
                                return;
                            }
                            if (res.code == 1) {
                                wx.showToast({
                                    title: res.msg,
                                    image: "/images/icon-warning.png",
                                });
                                return;
                            }
                        }
                    });
                }else {
                    wx.hideLoading();
                    wx.showToast({
                        title: res.msg,
                        image: "/images/icon-warning.png",
                    });
                    return;
                }

            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },



    radioChange: function (e) {
        console.log('radio发生change事件，携带value值为：', e.detail.value)
        let value = e.detail.value;
        this.data.pay_type = e.detail.value;
        this.setData({
            pay_type: value, 
        })
      },
      peisongChange: function (e) {
        console.log('radio发生change事件，携带value值为：', e.detail.value)
        let value = e.detail.value;
        this.data.peisongType = e.detail.value;
        if(this.data.peisongType == 'kd'){
            this.data.offline = 0;
        }else if (this.data.peisongType == 'zt'){
            this.data.offline = 1;
        }else {
            this.data.offline = 2;
        }
        this.getOrderData(this.data.options);
        this.setData({
            peisongType: value, 
        })
      },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var page = this;
        page.getOrderData(page.data.options);
        console.log("调用了on Show")
    },

    getOrderData: function (options) {
		var access_token = wx.getStorageSync("access_token");
        var page = this;
        var address_id = 0;
        if (page.data.address && page.data.address.id)
            address_id = page.data.address.id;
        if (options.cart_id_list) {
          console.log("获取购物车信息");
            console.log(options.cart_id_list);
            var cart_id_list =options.cart_id_list;
            wx.showLoading({
                title: "正在加载",
                mask: true,
            });
            console.log("offline=========")
            console.log(page.data.offline)
            app.request({
                url: api.order.submit_preview,
                data: {
					userid:access_token,
                    cartIds: options.cart_id_list,
                    type:2,
                    addressId: address_id,
                    offline: page.data.offline
                },
                success: function (res) {
                    wx.hideLoading();
                    if (res.code == 200) {
                        page.setData({
                            cart_id_list: res.data.cart_id_list,
                            total_price: res.data.calcAmount.totalAmount,
                            goods_list: res.data.cartPromotionItemList,
                            jifen: res.data.integrationConsumeSetting,
                            address: res.data.address,//这里主要是为了获取默认收货地址
                            calcAmount:res.data.calcAmount,
                            coupon_list: res.data.couponHistoryDetailList,
                        });
                        var address = wx.getStorageSync("picker_address");
                        if (address) {
                            this.data.address = address;
                            page.setData({
                                address: address
                            });
                            wx.removeStorageSync("picker_address");
                        }
                        if (res.data.send_type == 1) {//仅快递
                            page.setData({
                                offline: 0,
                            });
                        }
                        if (res.data.send_type == 2) {//仅自提
                            page.setData({
                                offline: 1,
                            });
                        }
                    }
                    if (res.code !=200) {
                        wx.showModal({
                            title: "提示",
                            content: res.msg,
                            showCancel: false,
                            confirmText: "返回",
                            success: function (res) {
                                if (res.confirm) {
                                    wx.navigateBack({
                                        delta: 1,
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        if (options.goods_info) {
          console.log("获取下单信息");
         

            var info  = JSON.parse(options.goods_info);
            console.log(info);
          console.log("获取数量信息");
          console.log(info.count);
            wx.showLoading({
                title: "正在加载",
                mask: true,
            });
            app.request({
                url: api.order.submit_preview,
                data: {
				    userid:access_token,
                    cartId:info.cartId,
                    type:1,
                    count: info.count,
                    addressid: address_id,
                    offline: page.data.offline
                },
                success: function (res) {
                    wx.hideLoading();
                  console.log("获取下单信息结果");
                  console.log(res)
                  console.log("获取下单信息结果2");

                    if (res.code == 200) {
                        page.setData({
                            total_price: res.data.calcAmount.totalAmount,
                            goods_list: res.data.cartPromotionItemList,
                            jifen: res.data.integrationConsumeSetting,
                            address: res.data.address,
                            calcAmount:res.data.calcAmount,
                            coupon_list: res.data.couponHistoryDetailList,

                        });
                        var address = wx.getStorageSync("picker_address");
                        if (address) {
                            page.setData({
                                address: address
                            });
                            wx.removeStorageSync("picker_address");
                        }
                        if (res.data.send_type == 1) {//仅快递
                            page.setData({
                                offline: 0,
                            });
                        }
                        if (res.data.send_type == 2) {//仅自提
                            page.setData({
                                offline: 1,
                            });
                        }
                    }
                    if (res.code !=200 ) {
                        wx.showModal({
                            title: "提示",
                            content: res.msg,
                            showCancel: false,
                            confirmText: "返回",
                            success: function (res) {
                                if (res.confirm) {
                                    wx.navigateBack({
                                        delta: 1,
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
    },

    copyText: function (e) {
        var text = e.currentTarget.dataset.text;
        if (!text)
            return;
        wx.setClipboardData({
            data: text,
            success: function () {
                wx.showToast({
                    title: "已复制内容",
                });
            },
            fail: function () {
                wx.showToast({
                    title: "复制失败",
                    image: "/images/icon-warning.png",
                });
            },
        });
    },

    showCouponPicker: function () {
        var page = this;
        if (page.data.coupon_list && page.data.coupon_list.length > 0) {
            page.setData({
                show_coupon_picker: true,
            });
        }
    },

    pickCoupon: function (e) {
		
        var page = this;
        var index = e.currentTarget.dataset.index;

        if (index == '-1' || index == -1) {
            page.setData({
                picker_coupon: false,
                show_coupon_picker: false,
            });
        } else {
            page.setData({
                picker_coupon: page.data.coupon_list[index].coupon,
                show_coupon_picker: false,
                new_total_price: parseFloat((page.data.total_price - page.data.coupon_list[index].coupon.amount).toFixed(2)),
            });
        }
		
    },

    numSub: function (num1, num2, length) {
        return 100;
    },
    showShop: function (e) {
        var page = this;
        if (page.data.shop_list && page.data.shop_list.length > 1) {
            page.setData({
                show_shop: true,
            });
        }
    },
    goChongzhi: function (e) {
        var page = this;
          wx.redirectTo({                  
            url: '/pages/invest/invest'
                                      })
                                     
       
    },
    pickShop: function (e) {
        var page = this;
        var index = e.currentTarget.dataset.index;
        if (index == '-1' || index == -1) {
            page.setData({
                shop: false,
                show_shop: false,
            });
        } else {
            page.setData({
                shop: page.data.shop_list[index],
                show_shop: false,
            });
        }
    }

});